package cn.cool.middleware.biz_exception_retry.trigger.listener;

import cn.cool.middleware.biz_exception_retry.config.BizExceptionRetryConfig;
import cn.cool.middleware.biz_exception_retry.domain.IBizExceptionRetryModuleService;
import cn.cool.middleware.biz_exception_retry.domain.IBizExceptionRetryTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 业务异常重试定时任务
 */
@Slf4j
public class BizExceptionRetryJob {
    @Resource
    private IBizExceptionRetryModuleService bizExceptionRetryModuleService;

    @Resource
    private IBizExceptionRetryTaskService bizExceptionRetryTaskService;

    @Resource
    private BizExceptionRetryConfig config;

    @Scheduled(cron = "${biz.exception.retry.job.cron:0 0/5 * * * ?}", zone = "${biz.exception.retry.job.cron.zone:UTC}")
    public void bizExceptionRetryJob() {
        String exceptionModule = config.getExceptionModule();
        Integer interValMillis = config.getInterValMillis();
        // 采用 MySQL 作为分布式锁
        boolean isLock = bizExceptionRetryModuleService.tryLock(exceptionModule, interValMillis);
        try {
            if (isLock) {
                log.info("[@BizExceptionRetry] 开启业务异常重试");
                bizExceptionRetryTaskService.executeBizExceptionRetryTask();
                // 程序sleep 5s，防止锁失效 todo
                TimeUnit.SECONDS.sleep(5);
            }
        } catch (Throwable throwable) {
            log.error("[@BizExceptionRetry] 定时业务异常重试失败", throwable);
        }finally {
            if (isLock) {
                bizExceptionRetryModuleService.unLock(exceptionModule);
            }
        }
    }
}
